﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.IO;
using ImageUploader.domain;


namespace ImageUploader.GUI
{
    public partial class EditUsersForm : Form
    {
        private User myUser;
        private List<User> users = new List<User>();
        private List<User> filteredList;
        private bool enableSave;
        private DomainController domainController;

        public EditUsersForm(DomainController dc)
        {
            this.domainController = dc;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            InitializeComponent();
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                pictureBoxNew.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                //dataGridViewUsers.CurrentRow.Cells["JpgPhoto"].Value = ms.ToArray();
                dataGridViewUsers.SelectedRows[0].Cells["JpgPhoto"].Value = ms.ToArray();
                textBoxImage.Text = "";
                labelMessage.Text = "succesfully saved " + textBoxImage.Text + " to " + myUser.CN;
                pictureBoxOld.Image = ImageOperations.GetImageFromByteArray(myUser.JpgPhoto);
                pictureBoxNew.Image = null;
            }
            catch (Exception ex)
            {
                labelMessage.Text = ex.Message;
            }
        }


        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtFilter_TextChanged(object sender, EventArgs e)
        {
            filteredList = domainController.GetUsers().Where(u => u.AllStringProps.ToLower().Contains(txtFilter.Text.ToLower())).ToList();
            FillGridView();
        }

        private void buttonBrowseImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "JPG afbeeldingen (*.jpeg, *.jpg)|*jpeg;*.jpg";
            if (ofd.ShowDialog() == DialogResult.OK)
                textBoxImage.Text = ofd.FileName;
        }

        private void textBoxImage_TextChanged(object sender, EventArgs e)
        {
            if (textBoxImage.Text.Length > 0)
                if (File.Exists(textBoxImage.Text))
                {
                    try
                    {
                        string extention = new FileInfo(textBoxImage.Text).Extension;
                        Image img = Image.FromFile(textBoxImage.Text);
                        if (img.Width != 96 || img.Height != 96
                            | !img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg)
                            | !(extention.Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) || extention.Equals(".jpeg", StringComparison.CurrentCultureIgnoreCase)))
                            throw new Exception("Verkeerd formaat, moet 96 * 96 JPG-file zijn.");
                        pictureBoxNew.Image = Image.FromFile(textBoxImage.Text);
                        labelMessage.Text = "";
                        enableSave = true;
                        UpdateSavebuttonEnabledState();
                        return;
                    }
                    catch (Exception ex)
                    {
                        labelMessage.Text = ex.Message;
                    }
                }
                else
                    labelMessage.Text = "File does not exist";
            else
                labelMessage.Text = "";

            enableSave = false;
            pictureBoxNew.Image = null;
            UpdateSavebuttonEnabledState();
        }

        private void UpdateSavebuttonEnabledState()
        {
            buttonSave.Enabled = enableSave;
        }

        private void ImageUploader_Load(object sender, EventArgs e)
        {
            ReloadGrid();
           // RefreshGrid();
        }

        private void dataGridViewUsers_SelectionChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void dataGridViewUsers_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            EditForm ef = new EditForm(myUser);
            ef.Show();
            if (ef.DialogResult == DialogResult.OK || ef.DialogResult == DialogResult.Cancel)
                dataGridViewUsers.Refresh();

            ef.FormClosed += new FormClosedEventHandler(ef_FormClosed);
            ClearText();
        }

        public void ef_FormClosed(object sender, FormClosedEventArgs e)
        {
            ReloadGrid();
        }

        private void FillGridView()
        {
            dataGridViewUsers.DataSource = filteredList;
            dataGridViewUsers.Columns["street"].Visible = false;
            dataGridViewUsers.Columns["Province"].Visible = false;
            dataGridViewUsers.Columns["Place"].Visible = false;
            dataGridViewUsers.Columns["Office"].Visible = false;
            dataGridViewUsers.Columns["Country"].Visible = false;
            dataGridViewUsers.Columns["PostalCode"].Visible = false;
            dataGridViewUsers.Columns["PostOfficeBox"].Visible = false;
            dataGridViewUsers.Columns["JpgPhoto"].Visible = false;
            dataGridViewUsers.Columns["AllStringProps"].Visible = false;
            dataGridViewUsers.Columns["Description"].Visible = false;
            dataGridViewUsers.Columns["Initials"].Visible = false;
            dataGridViewUsers.Columns["Telnr"].Visible = false;
            dataGridViewUsers.Columns["HomePage"].Visible = false;
            dataGridViewUsers.Columns["DirectoryEntry"].Visible = false;
            dataGridViewUsers.Columns["userPrincipalName"].Visible = false;
            dataGridViewUsers.Columns["SearchResult"].Visible = false;
            dataGridViewUsers.Columns["AccountEnabled"].Visible = false;
            //dataGridViewUsers.Columns[16].Visible = false;
            //dataGridViewUsers.Columns[17].Visible = false;
            dataGridViewUsers.Refresh();
            
        }

        private void ClearText()
        {
            labelMessage.Text = "";
            txtFilter.Text = "";
            textBoxImage.Text = "";
        }

        private void btnNewUser_Click(object sender, EventArgs e)
        {
            ClearText();
            AddNewUser anu = new AddNewUser(domainController);
            anu.Show();
            
        }

        private void buttonRemove_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to remove this user?", "Confirm removal", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                try
                {
                    labelMessage.Text = "";
                    domainController.RemoveUser(myUser);
                    ReloadGrid();
                    ClearText();
                }
                catch (Exception ex)
                {
                    labelMessage.Text = "Can't remove this built-in useraccount";
                    MessageBox.Show(ex.Message);
                }
            }
            
        }
        private void ReloadGrid()
        {
            filteredList = domainController.GetUsers();
            FillGridView();
            
        }

        private void RefreshPage()
        {
            RefreshGrid();
        }

        private void RefreshGrid()
        {
            textBoxImage.Text = "";
            labelMessage.Text = "";
            if (dataGridViewUsers.SelectedRows.Count > 0)
            {
                myUser = (User)((DataGridView)dataGridViewUsers).CurrentRow.DataBoundItem;
                if (myUser.JpgPhoto != null)
                    pictureBoxOld.Image = ImageOperations.GetImageFromByteArray(myUser.JpgPhoto);
                else
                {
                    pictureBoxOld.Image = null;
                    pictureBoxNew.Image = null;
                }   
            }
            else
            {
                myUser = null;
                pictureBoxOld.Image = null;
                pictureBoxNew.Image = null;
            }
        }

        private void buttonPW_Click(object sender, EventArgs e)
        {
            List<User> lst = new List<User>();
            lst.Add(myUser);
            EnterPassword ep = new EnterPassword(lst);
            ep.FormClosed += new FormClosedEventHandler(ep_FormClosed);
            ep.Show();
        }

        private void ep_FormClosed(object sender, FormClosedEventArgs e)
        {
            List<User> failedUsers=((EnterPassword)sender).FailedUsers;
            if (failedUsers.Count > 0)
            {
                string users="";
                int counter = 0;
                foreach (User u in failedUsers)
                {
                    users += (u.CN + ((counter == 0 || counter==failedUsers.Count) ? "" : ",") + " ");
                    counter++;
                }
                MessageBox.Show("Set password failed for these users:\n" + users);
            }
        }

        private void btnMassPassword_Click(object sender, EventArgs e)
        {
            EnterPassword ep = new EnterPassword( domainController.GetNonSystemCriticalUsers(null));
            ep.FormClosed += new FormClosedEventHandler(ep_FormClosed);
            ep.Show();
        }
    }
}
